package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.ProductEvent;
import com.ruoyi.system.mapper.ProductEventMapper;
import com.ruoyi.system.service.IProductEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ProductEventServiceImpl implements IProductEventService {

    @Autowired
    private ProductEventMapper productEventMapper;

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public List<ProductEvent> queryList(ProductEvent productEvent) {
        List<ProductEvent> productEvents = productEventMapper.queryList(productEvent);
        if (CollUtil.isNotEmpty(productEvents)){
            for (ProductEvent event : productEvents) {
                event.setParamList(JSONUtil.parseArray(event.getParam()));
            }
        }
        return productEvents;
    }

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public ProductEvent getOne(ProductEvent productEvent) {
        ProductEvent event = productEventMapper.getOne(productEvent);
        return event == null ? new ProductEvent() : event;
    }

    @Override
    public Boolean add(ProductEvent productEvent) {
        return productEventMapper.add(productEvent) > 0;
    }

    @Override
    @UserDataIsolation
    public Boolean update(ProductEvent productEvent) {
        return productEventMapper.update(productEvent) > 0;
    }

    @Override
    @UserDataIsolation
    public Boolean delete(ProductEvent productEvent) {
        return productEventMapper.delete(productEvent) > 0;
    }

    @Override
    @UserDataIsolation
    public void checkIsExit(ProductEvent productEvent) {
        ProductEvent result = productEventMapper.checkIsExit(productEvent);
        if (result == null) {
            return;
        }
        if (productEvent.getId() == null || productEvent.getId().compareTo(result.getId()) != 0) {
            if (StrUtil.equals(productEvent.getName(), result.getName())) {
                throw new CustomException("事件名称已经存在");
            }
            if (StrUtil.equals(productEvent.getTerminalIdentifier(), result.getTerminalIdentifier())) {
                throw new CustomException("终端侧标识符已经存在");
            }
            if (StrUtil.equals(productEvent.getUserIdentifier(), result.getUserIdentifier())) {
                throw new CustomException("用户侧标识符已经存在");
            }
        }
    }
}
